<?php

namespace core;

class View
{
    protected string $viewFile;
    protected array $data;

    public function __construct(string $viewName, array $data = [])
    {
        $this->viewFile = APP_PATH . '/view/' . $viewName . '.php';
        $this->data = $data;
    }

    /**
     * 渲染视图
     */
    public function render(): void
    {
        $viewPath = $this->viewFile;
        
        // **安全**：防止路径遍历 (尽管路由已做限制，但双重检查更好)
        $realViewPath = realpath($viewPath);
        if ($realViewPath === false || strpos($realViewPath, realpath(APP_PATH . '/view')) !== 0) {
            throw new \Exception("View file not found or path is invalid: {$viewPath}");
        }

        // 将 $data 数组的键解压为变量，以便在视图中直接使用
        // 例如 $data['name'] 变为 $name
        extract($this->data, EXTR_SKIP);
        
        require $realViewPath; // $realViewPath 是安全的
    }
}